
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" lang="zh_Hans">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>管理静态文件（比如图片、JavaScript、CSS） &#8212; Django 3.2.11.dev 文档</title>
    <link rel="stylesheet" href="../../_static/default.css" type="text/css" />
    <link rel="stylesheet" href="../../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../../" src="../../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../../_static/jquery.js"></script>
    <script type="text/javascript" src="../../_static/underscore.js"></script>
    <script type="text/javascript" src="../../_static/doctools.js"></script>
    <script type="text/javascript" src="../../_static/language_data.js"></script>
    <link rel="index" title="索引" href="../../genindex.html" />
    <link rel="search" title="搜索" href="../../search.html" />
    <link rel="next" title="部署静态文件" href="deployment.html" />
    <link rel="prev" title="复写模板" href="../overriding-templates.html" />



 
<script src="../../templatebuiltins.js"></script>
<script>
(function($) {
    if (!django_template_builtins) {
       // templatebuiltins.js missing, do nothing.
       return;
    }
    $(document).ready(function() {
        // Hyperlink Django template tags and filters
        var base = "../../ref/templates/builtins.html";
        if (base == "#") {
            // Special case for builtins.html itself
            base = "";
        }
        // Tags are keywords, class '.k'
        $("div.highlight\\-html\\+django span.k").each(function(i, elem) {
             var tagname = $(elem).text();
             if ($.inArray(tagname, django_template_builtins.ttags) != -1) {
                 var fragment = tagname.replace(/_/, '-');
                 $(elem).html("<a href='" + base + "#" + fragment + "'>" + tagname + "</a>");
             }
        });
        // Filters are functions, class '.nf'
        $("div.highlight\\-html\\+django span.nf").each(function(i, elem) {
             var filtername = $(elem).text();
             if ($.inArray(filtername, django_template_builtins.tfilters) != -1) {
                 var fragment = filtername.replace(/_/, '-');
                 $(elem).html("<a href='" + base + "#" + fragment + "'>" + filtername + "</a>");
             }
        });
    });
})(jQuery);</script>

  </head><body>

    <div class="document">
  <div id="custom-doc" class="yui-t6">
    <div id="hd">
      <h1><a href="../../index.html">Django 3.2.11.dev 文档</a></h1>
      <div id="global-nav">
        <a title="Home page" href="../../index.html">Home</a>  |
        <a title="Table of contents" href="../../contents.html">Table of contents</a>  |
        <a title="Global index" href="../../genindex.html">Index</a>  |
        <a title="Module index" href="../../py-modindex.html">Modules</a>
      </div>
      <div class="nav">
    &laquo; <a href="../overriding-templates.html" title="复写模板">previous</a>
     |
    <a href="../index.html" title="操作指南" accesskey="U">up</a>
   |
    <a href="deployment.html" title="部署静态文件">next</a> &raquo;</div>
    </div>

    <div id="bd">
      <div id="yui-main">
        <div class="yui-b">
          <div class="yui-g" id="howto-static-files-index">
            
  <div class="section" id="s-managing-static-files-e-g-images-javascript-css">
<span id="managing-static-files-e-g-images-javascript-css"></span><h1>管理静态文件（比如图片、JavaScript、CSS）<a class="headerlink" href="#managing-static-files-e-g-images-javascript-css" title="永久链接至标题">¶</a></h1>
<p>网站通常需要提供类似图片，JavaScript 或 CSS 的额外文件服务。在 Django 中，我们将这些文件称为“静态文件”。Django 提供了 <a class="reference internal" href="../../ref/contrib/staticfiles.html#module-django.contrib.staticfiles" title="django.contrib.staticfiles: An app for handling static files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">django.contrib.staticfiles</span></code></a> 帮你管理它们。</p>
<p>本页介绍如何为这些静态文件提供服务。</p>
<div class="section" id="s-configuring-static-files">
<span id="configuring-static-files"></span><h2>配置静态文件<a class="headerlink" href="#configuring-static-files" title="永久链接至标题">¶</a></h2>
<ol class="arabic">
<li><p class="first">确保 <a class="reference internal" href="../../ref/settings.html#std:setting-INSTALLED_APPS"><code class="xref std std-setting docutils literal notranslate"><span class="pre">INSTALLED_APPS</span></code></a> 包含了 <code class="docutils literal notranslate"><span class="pre">django.contrib.staticfiles</span></code>。</p>
</li>
<li><p class="first">在配置文件中，定义 <a class="reference internal" href="../../ref/settings.html#std:setting-STATIC_URL"><code class="xref std std-setting docutils literal notranslate"><span class="pre">STATIC_URL</span></code></a>，例子:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">STATIC_URL</span> <span class="o">=</span> <span class="s1">&#39;/static/&#39;</span>
</pre></div>
</div>
</li>
<li><p class="first">在模板中，用 <a class="reference internal" href="../../ref/templates/builtins.html#std:templatetag-static"><code class="xref std std-ttag docutils literal notranslate"><span class="pre">static</span></code></a> 模板标签基于配置 <a class="reference internal" href="../../ref/settings.html#std:setting-STATICFILES_STORAGE"><code class="xref std std-setting docutils literal notranslate"><span class="pre">STATICFILES_STORAGE</span></code></a> 位给定的相对路径构建 URL。</p>
<div class="highlight-html+django notranslate" id="staticfiles-in-templates"><div class="highlight"><pre><span></span><span class="cp">{%</span> <span class="k">load</span> <span class="nv">static</span> <span class="cp">%}</span>
<span class="p">&lt;</span><span class="nt">img</span> <span class="na">src</span><span class="o">=</span><span class="s">&quot;</span><span class="cp">{%</span> <span class="k">static</span> <span class="s1">&#39;my_app/example.jpg&#39;</span> <span class="cp">%}</span><span class="s">&quot;</span> <span class="na">alt</span><span class="o">=</span><span class="s">&quot;My image&quot;</span><span class="p">&gt;</span>
</pre></div>
</div>
</li>
<li><p class="first">将你的静态文件保存至程序中名为 <code class="docutils literal notranslate"><span class="pre">static</span></code> 的目录中。例如 <code class="docutils literal notranslate"><span class="pre">my_app/static/my_app/example.jpg</span></code>。</p>
</li>
</ol>
<div class="admonition-serving-the-files admonition">
<p class="first admonition-title">为这些文件提供服务</p>
<p>除了这些配置步骤外，你还需要实际地为这些文件提供服务。</p>
<p>开发时，使用 <a class="reference internal" href="../../ref/contrib/staticfiles.html#module-django.contrib.staticfiles" title="django.contrib.staticfiles: An app for handling static files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">django.contrib.staticfiles</span></code></a>，这一般会在 <a class="reference internal" href="../../ref/settings.html#std:setting-DEBUG"><code class="xref std std-setting docutils literal notranslate"><span class="pre">DEBUG</span></code></a> is set to <code class="docutils literal notranslate"><span class="pre">True</span></code> 情况下由 <a class="reference internal" href="../../ref/django-admin.html#django-admin-runserver"><code class="xref std std-djadmin docutils literal notranslate"><span class="pre">runserver</span></code></a> 自动完成（参考 <a class="reference internal" href="../../ref/contrib/staticfiles.html#django.contrib.staticfiles.views.serve" title="django.contrib.staticfiles.views.serve"><code class="xref py py-func docutils literal notranslate"><span class="pre">django.contrib.staticfiles.views.serve()</span></code></a>）。</p>
<p>该方法 <strong>极度低效</strong> 且 <strong>不怎么安全</strong>，所以这 <strong>不适合生产环境</strong>。</p>
<p class="last">参考 <a class="reference internal" href="deployment.html"><span class="doc">部署静态文件</span></a> 了解如何正确地在生产环境提供静态文件服务的策略。</p>
</div>
<p>你的工程可能包含未与任何应用绑定的静态资源。除了在 apps 中使用 <code class="docutils literal notranslate"><span class="pre">static/</span></code> 目录，你可以在配置文件中定义一个目录列表 (<a class="reference internal" href="../../ref/settings.html#std:setting-STATICFILES_DIRS"><code class="xref std std-setting docutils literal notranslate"><span class="pre">STATICFILES_DIRS</span></code></a>) ，Django 会从中寻找静态文件。例子:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">STATICFILES_DIRS</span> <span class="o">=</span> <span class="p">[</span>
    <span class="n">BASE_DIR</span> <span class="o">/</span> <span class="s2">&quot;static&quot;</span><span class="p">,</span>
    <span class="s1">&#39;/var/www/static/&#39;</span><span class="p">,</span>
<span class="p">]</span>
</pre></div>
</div>
<p>参考 <a class="reference internal" href="../../ref/settings.html#std:setting-STATICFILES_FINDERS"><code class="xref std std-setting docutils literal notranslate"><span class="pre">STATICFILES_FINDERS</span></code></a> 配置的文档了解 <code class="docutils literal notranslate"><span class="pre">staticfiles</span></code> 是如何找到你的文件的细节。</p>
<div class="admonition-static-file-namespacing admonition">
<p class="first admonition-title">静态文件命名空间</p>
<p>现在，我们 <em>也许</em> 能直接将静态文件放入 <code class="docutils literal notranslate"><span class="pre">my_app/static/</span></code> 目录（而不是创建另一个 <code class="docutils literal notranslate"><span class="pre">my_app</span></code> 子目录），不过这实际上是个坏主意。Django 会使用第一个名字匹配的静态文件，若你在 <em>不同的</em> 应用程序中有一个同名静态文件，Django 无力区分它们。我们需要为 Django 指出正确的那个，而最好的方式就是使用 <em>命名空间</em>。也就是说，将这些静态文件放在 <em>另一个</em> 以应用程序名本身命名的目录下。</p>
<p class="last">你可以通过指定 <a class="reference internal" href="../../ref/settings.html#staticfiles-dirs-prefixes"><span class="std std-ref">prefixes</span></a> 在 <a class="reference internal" href="../../ref/settings.html#std:setting-STATICFILES_DIRS"><code class="xref std std-setting docutils literal notranslate"><span class="pre">STATICFILES_DIRS</span></code></a> 中为静态资源做命名。</p>
</div>
</div>
<div class="section" id="s-serving-static-files-during-development">
<span id="s-serving-static-files-in-development"></span><span id="serving-static-files-during-development"></span><span id="serving-static-files-in-development"></span><h2>开发时提供静态文件服务<a class="headerlink" href="#serving-static-files-during-development" title="永久链接至标题">¶</a></h2>
<p>若你使用了前文所述的 <a class="reference internal" href="../../ref/contrib/staticfiles.html#module-django.contrib.staticfiles" title="django.contrib.staticfiles: An app for handling static files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">django.contrib.staticfiles</span></code></a>， <a class="reference internal" href="../../ref/django-admin.html#django-admin-runserver"><code class="xref std std-djadmin docutils literal notranslate"><span class="pre">runserver</span></code></a> 会在 <a class="reference internal" href="../../ref/settings.html#std:setting-DEBUG"><code class="xref std std-setting docutils literal notranslate"><span class="pre">DEBUG</span></code></a> 为 <code class="docutils literal notranslate"><span class="pre">True</span></code> 时自动处理。若你未在 <a class="reference internal" href="../../ref/settings.html#std:setting-INSTALLED_APPS"><code class="xref std std-setting docutils literal notranslate"><span class="pre">INSTALLED_APPS</span></code></a> 中包含 <code class="docutils literal notranslate"><span class="pre">django.contrib.staticfiles</span></code>，你仍能手动通过 <a class="reference internal" href="../../ref/views.html#django.views.static.serve" title="django.views.static.serve"><code class="xref py py-func docutils literal notranslate"><span class="pre">django.views.static.serve()</span></code></a> 为静态文件提供服务。</p>
<p>这不适合生产环境！常见的部署策略请参考 <a class="reference internal" href="deployment.html"><span class="doc">部署静态文件</span></a>。</p>
<p>例如，若 <a class="reference internal" href="../../ref/settings.html#std:setting-STATIC_URL"><code class="xref std std-setting docutils literal notranslate"><span class="pre">STATIC_URL</span></code></a> 为 <code class="docutils literal notranslate"><span class="pre">/static/</span></code>，你能通过添加以下代码片段至 urls.py 完成目的:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.conf</span> <span class="kn">import</span> <span class="n">settings</span>
<span class="kn">from</span> <span class="nn">django.conf.urls.static</span> <span class="kn">import</span> <span class="n">static</span>

<span class="n">urlpatterns</span> <span class="o">=</span> <span class="p">[</span>
    <span class="c1"># ... the rest of your URLconf goes here ...</span>
<span class="p">]</span> <span class="o">+</span> <span class="n">static</span><span class="p">(</span><span class="n">settings</span><span class="o">.</span><span class="n">STATIC_URL</span><span class="p">,</span> <span class="n">document_root</span><span class="o">=</span><span class="n">settings</span><span class="o">.</span><span class="n">STATIC_ROOT</span><span class="p">)</span>
</pre></div>
</div>
<div class="admonition note">
<p class="first admonition-title">注解</p>
<p>该助手函数只能在 debug 模式下生效，且要求前缀是本地的（例如 <code class="docutils literal notranslate"><span class="pre">/static/</span></code>），不是一个 URL (例如 <code class="docutils literal notranslate"><span class="pre">http://static.example.com/</span></code>)。</p>
<p class="last">当然，助手函数只为实际的 <a class="reference internal" href="../../ref/settings.html#std:setting-STATIC_ROOT"><code class="xref std std-setting docutils literal notranslate"><span class="pre">STATIC_ROOT</span></code></a> 目录提供服务；它不会像 <a class="reference internal" href="../../ref/contrib/staticfiles.html#module-django.contrib.staticfiles" title="django.contrib.staticfiles: An app for handling static files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">django.contrib.staticfiles</span></code></a> 一样搜索静态文件。</p>
</div>
</div>
<div class="section" id="s-serving-files-uploaded-by-a-user-during-development">
<span id="s-serving-uploaded-files-in-development"></span><span id="serving-files-uploaded-by-a-user-during-development"></span><span id="serving-uploaded-files-in-development"></span><h2>开发期间保存用户上传的文件<a class="headerlink" href="#serving-files-uploaded-by-a-user-during-development" title="永久链接至标题">¶</a></h2>
<p>开发期间，你能用 <a class="reference internal" href="../../ref/views.html#django.views.static.serve" title="django.views.static.serve"><code class="xref py py-func docutils literal notranslate"><span class="pre">django.views.static.serve()</span></code></a> 视图为用户上传的媒体文件提供服务。</p>
<p>这不适合生产环境！常见的部署策略请参考 <a class="reference internal" href="deployment.html"><span class="doc">部署静态文件</span></a>。</p>
<p>例如，如果您的配置 <a class="reference internal" href="../../ref/settings.html#std:setting-MEDIA_URL"><code class="xref std std-setting docutils literal notranslate"><span class="pre">MEDIA_URL</span></code></a> 定义为 <code class="docutils literal notranslate"><span class="pre">/media/</span></code> ，您可以通过将以下代码段添加到您的配置 <a class="reference internal" href="../../ref/settings.html#std:setting-ROOT_URLCONF"><code class="xref std std-setting docutils literal notranslate"><span class="pre">ROOT_URLCONF</span></code></a>:: 。</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.conf</span> <span class="kn">import</span> <span class="n">settings</span>
<span class="kn">from</span> <span class="nn">django.conf.urls.static</span> <span class="kn">import</span> <span class="n">static</span>

<span class="n">urlpatterns</span> <span class="o">=</span> <span class="p">[</span>
    <span class="c1"># ... the rest of your URLconf goes here ...</span>
<span class="p">]</span> <span class="o">+</span> <span class="n">static</span><span class="p">(</span><span class="n">settings</span><span class="o">.</span><span class="n">MEDIA_URL</span><span class="p">,</span> <span class="n">document_root</span><span class="o">=</span><span class="n">settings</span><span class="o">.</span><span class="n">MEDIA_ROOT</span><span class="p">)</span>
</pre></div>
</div>
<div class="admonition note">
<p class="first admonition-title">注解</p>
<p class="last">该助手函数只能在 debug 模式下生效，且要求前缀是本地的（例如 <code class="docutils literal notranslate"><span class="pre">/static/</span></code>），不是一个 URL (例如 <code class="docutils literal notranslate"><span class="pre">http://media.example.com/</span></code>)。</p>
</div>
</div>
<div class="section" id="s-testing">
<span id="s-staticfiles-testing-support"></span><span id="testing"></span><span id="staticfiles-testing-support"></span><h2>测试<a class="headerlink" href="#testing" title="永久链接至标题">¶</a></h2>
<p>运行使用真实 HTTP 请求（而不是内置的测试客户端，即内置的 <a class="reference internal" href="../../topics/testing/tools.html#django.test.LiveServerTestCase" title="django.test.LiveServerTestCase"><code class="xref py py-class docutils literal notranslate"><span class="pre">LiveServerTestCase</span></code></a>）的测试用例时，静态资源要与剩余内容分别提供服务，这样，测试环境才能尽量重现真实的问题。但 <code class="docutils literal notranslate"><span class="pre">LiveServerTestCase</span></code> 只拥有非常基本的为静态文件提供服务的能力：它并不知道 <code class="docutils literal notranslate"><span class="pre">staticfiles</span></code> 应用的查找功能，且总是假设静态内容已被收集至 <a class="reference internal" href="../../ref/settings.html#std:setting-STATIC_ROOT"><code class="xref std std-setting docutils literal notranslate"><span class="pre">STATIC_ROOT</span></code></a> 目录下。</p>
<p>因此， <code class="docutils literal notranslate"><span class="pre">staticfiles</span></code> 自带了 <a class="reference internal" href="../../ref/contrib/staticfiles.html#django.contrib.staticfiles.testing.StaticLiveServerTestCase" title="django.contrib.staticfiles.testing.StaticLiveServerTestCase"><code class="xref py py-class docutils literal notranslate"><span class="pre">django.contrib.staticfiles.testing.StaticLiveServerTestCase</span></code></a>，这是一个内置子类，能够透明地以类似我们在开发阶段 <code class="docutils literal notranslate"><span class="pre">DEBUG</span> <span class="pre">=</span> <span class="pre">True</span></code> 时获得的方式为所有静态资源在测试期间提供服务。即无需先用 <a class="reference internal" href="../../ref/contrib/staticfiles.html#django-admin-collectstatic"><code class="xref std std-djadmin docutils literal notranslate"><span class="pre">collectstatic</span></code></a> 收集它们。</p>
</div>
<div class="section" id="s-deployment">
<span id="deployment"></span><h2>部署<a class="headerlink" href="#deployment" title="永久链接至标题">¶</a></h2>
<p><a class="reference internal" href="../../ref/contrib/staticfiles.html#module-django.contrib.staticfiles" title="django.contrib.staticfiles: An app for handling static files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">django.contrib.staticfiles</span></code></a> 提供了一个便利的管理命令，用于将静态文件收集至独立目录，方便你为它们提供服务。</p>
<ol class="arabic">
<li><p class="first">将 <a class="reference internal" href="../../ref/settings.html#std:setting-STATIC_ROOT"><code class="xref std std-setting docutils literal notranslate"><span class="pre">STATIC_ROOT</span></code></a> 配置成你喜欢的目录，在这个目录提供服务，例如:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">STATIC_ROOT</span> <span class="o">=</span> <span class="s2">&quot;/var/www/example.com/static/&quot;</span>
</pre></div>
</div>
</li>
<li><p class="first">运行 <a class="reference internal" href="../../ref/contrib/staticfiles.html#django-admin-collectstatic"><code class="xref std std-djadmin docutils literal notranslate"><span class="pre">collectstatic</span></code></a> 管理命令:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span>$ python manage.py collectstatic
</pre></div>
</div>
<p>这将会把静态目录下的所有文件拷贝至 <a class="reference internal" href="../../ref/settings.html#std:setting-STATIC_ROOT"><code class="xref std std-setting docutils literal notranslate"><span class="pre">STATIC_ROOT</span></code></a> 目录。</p>
</li>
<li><p class="first">选一个 Web 服务器为这些文件提供服务。 文档 <a class="reference internal" href="deployment.html"><span class="doc">部署静态文件</span></a> 介绍了静态文件的常见部署策略。</p>
</li>
</ol>
</div>
<div class="section" id="s-learn-more">
<span id="learn-more"></span><h2>了解更多<a class="headerlink" href="#learn-more" title="永久链接至标题">¶</a></h2>
<p>本文档已覆盖基础和常见模式。对于所有配置项，命令，模板标签和其他包含在 <a class="reference internal" href="../../ref/contrib/staticfiles.html#module-django.contrib.staticfiles" title="django.contrib.staticfiles: An app for handling static files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">django.contrib.staticfiles</span></code></a> 碎片的全部细节，参考 <a class="reference internal" href="../../ref/contrib/staticfiles.html"><span class="doc">静态文件参考</span></a>。</p>
</div>
</div>


          </div>
        </div>
      </div>
      
        
          <div class="yui-b" id="sidebar">
            
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../../contents.html">Table of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">管理静态文件（比如图片、JavaScript、CSS）</a><ul>
<li><a class="reference internal" href="#configuring-static-files">配置静态文件</a></li>
<li><a class="reference internal" href="#serving-static-files-during-development">开发时提供静态文件服务</a></li>
<li><a class="reference internal" href="#serving-files-uploaded-by-a-user-during-development">开发期间保存用户上传的文件</a></li>
<li><a class="reference internal" href="#testing">测试</a></li>
<li><a class="reference internal" href="#deployment">部署</a></li>
<li><a class="reference internal" href="#learn-more">了解更多</a></li>
</ul>
</li>
</ul>

  <h4>上一个主题</h4>
  <p class="topless"><a href="../overriding-templates.html"
                        title="上一章">复写模板</a></p>
  <h4>下一个主题</h4>
  <p class="topless"><a href="deployment.html"
                        title="下一章">部署静态文件</a></p>
  <div role="note" aria-label="source link">
    <h3>本页</h3>
    <ul class="this-page-menu">
      <li><a href="../../_sources/howto/static-files/index.txt"
            rel="nofollow">显示源代码</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>快速搜索</h3>
    <div class="searchformwrapper">
    <form class="search" action="../../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="转向" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
              <h3>Last update:</h3>
              <p class="topless">12月 07, 2021</p>
          </div>
        
      
    </div>

    <div id="ft">
      <div class="nav">
    &laquo; <a href="../overriding-templates.html" title="复写模板">previous</a>
     |
    <a href="../index.html" title="操作指南" accesskey="U">up</a>
   |
    <a href="deployment.html" title="部署静态文件">next</a> &raquo;</div>
    </div>
  </div>

      <div class="clearer"></div>
    </div>
  </body>
</html>